package com.huaxin.hxmodulesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaxin.hxmodulesystem.dto.ResponseCode;
import com.huaxin.hxmodulesystem.dto.ResponseResult;
import com.huaxin.hxmodulesystem.dto.request.AddElectricianOrganizationFamilyReqDTO;
import com.huaxin.hxmodulesystem.dto.response.ElectricianScopeDTO;
import com.huaxin.hxmodulesystem.mapper.ElectricianArchivesMapper;
import com.huaxin.hxmodulesystem.mapper.ElectricianOrganizationFamilyMapper;
import com.huaxin.hxmodulesystem.mapping.ElectricianOrganizationFamilyMapping;
import com.huaxin.hxmodulesystem.models.ElectricianArchives;
import com.huaxin.hxmodulesystem.models.ElectricianOrganizationFamily;
import com.huaxin.hxmodulesystem.service.ElectricianOrganizationFamilyService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static org.springframework.util.StringUtils.hasText;

@Service
@RequiredArgsConstructor
public class ElectricianOrganizationFamilyServiceImpl extends ServiceImpl<ElectricianOrganizationFamilyMapper, ElectricianOrganizationFamily> implements ElectricianOrganizationFamilyService {

    private final ApplicationContext applicationContext;
    private final ElectricianOrganizationFamilyMapping electricianArchivesMapping;
    private final ElectricianArchivesMapper electricianArchivesMapper;

    // 添加电工组织关系
    @Override
    public ResponseResult<Boolean> addElectricianOrganizationFamily(AddElectricianOrganizationFamilyReqDTO in) {
        if (in == null) {
            return ResponseResult.parameterError(null, "参数不能为空");
        }
        if (StringUtils.isBlank(in.getElectricianId())) {
            return ResponseResult.parameterError(null, "电工ID不能为空");
        }
        if (StringUtils.isBlank(in.getFamilyId()) && StringUtils.isBlank(in.getOrgId())) {
            return ResponseResult.parameterError(null, "绑定对象不能为空");
        }
        // 校验电工和组织是否已绑定
        if (hasText(in.getOrgId()) && existsByOrgIdAndElectricianId(in.getOrgId(), in.getElectricianId())) {
            return ResponseResult.failure(ResponseCode.CONFLICT, "组织已绑定该电工", null);
        }
        // 校验电工和家庭是否已绑定
        if (hasText(in.getFamilyId()) && existsByFamilyIdAndElectricianId(in.getFamilyId(), in.getElectricianId())) {
            return ResponseResult.failure(ResponseCode.CONFLICT, "家庭已绑定该电工", null);
        }
        ElectricianOrganizationFamily electricianOrganizationFamily = electricianArchivesMapping.toEntity(in);
        return ResponseResult.ok(this.save(electricianOrganizationFamily));
    }

    //删除工电工组织关系
    @Override
    public ResponseResult<Boolean> deleteElectricianOrganizationFamily(String id) {
        if (StringUtils.isBlank(id)) {
            return ResponseResult.parameterError(null, "参数不能为空");
        }
        ElectricianOrganizationFamily electricianOrganizationFamily = this.baseMapper.selectById(id);
        if (electricianOrganizationFamily == null) {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "关系不存在", null);
        }
        if (applicationContext.getBean(ElectricianOrganizationFamilyService.class).removeById(id)) {
            return ResponseResult.ok(true);
        } else {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "删除失败，请稍后再试！", null);
        }
    }

    @Override
    public ResponseResult<Boolean> deleteByElectricianIdAndOrgId(String electricianId, String orgId, String familyId) {
        if (StringUtils.isBlank(electricianId)) {
            return ResponseResult.parameterError(null, "电工ID不能为空");
        }
        if (StringUtils.isBlank(familyId) && StringUtils.isBlank(orgId)) {
            return ResponseResult.parameterError(null, "绑定对象不能为空");
        }
        LambdaQueryWrapper<ElectricianOrganizationFamily> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ElectricianOrganizationFamily::getElectricianId, electricianId)
                .eq(hasText(orgId), ElectricianOrganizationFamily::getOrgId, orgId)
                .eq(hasText(familyId), ElectricianOrganizationFamily::getFamilyId, familyId);
        boolean removed = applicationContext.getBean(ElectricianOrganizationFamilyService.class).remove(queryWrapper);
        if (removed) {
            return ResponseResult.ok(true);
        } else {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "删除失败，请稍后再试！", null);
        }
    }

    @Override
    public ResponseResult<List<ElectricianScopeDTO>> electricianScopeList(String electricianId) {
        List<ElectricianScopeDTO> aggregateCustomerIdsList = new ArrayList<>();
        QueryWrapper<ElectricianArchives> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        if (StringUtils.isNotBlank(electricianId)) {
            queryWrapper.eq("id", electricianId);
        }
        List<ElectricianArchives> electricianArchivesList = electricianArchivesMapper.selectList(queryWrapper);
        for (ElectricianArchives item : electricianArchivesList) {
            ElectricianScopeDTO electricianScopeDTO = new ElectricianScopeDTO();
            electricianScopeDTO.setElectrician(item);
            QueryWrapper<ElectricianOrganizationFamily> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("electrician_id", item.getId());
            List<ElectricianOrganizationFamily> electricianOrganizationFamilyList = this.baseMapper.selectList(queryWrapper1);
            for (ElectricianOrganizationFamily item1 : electricianOrganizationFamilyList) {
                electricianScopeDTO.setFamilyList(this.baseMapper.GetFamilyeListByElectricianId(item1.getElectricianId()));
                electricianScopeDTO.setOrgList(this.baseMapper.GetOrgListByElectricianId(item1.getElectricianId()));
            }
            aggregateCustomerIdsList.add(electricianScopeDTO);
        }
        return ResponseResult.ok(aggregateCustomerIdsList);
    }

    /*
     * 根据家庭ID查询家庭专属电工ID列表
     */
    @Override
    public ResponseResult<List<String>> getElectriciansByFamilyIdAndOrgId(String familyId, String orgId) {
        if (StringUtils.isBlank(familyId)) {
            return ResponseResult.parameterError(null, "家庭ID不能为空");
        }
        if (StringUtils.isBlank(orgId)) {
            return ResponseResult.parameterError(null, "组织ID不能为空");
        }
        LambdaQueryWrapper<ElectricianOrganizationFamily> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ElectricianOrganizationFamily::getFamilyId, familyId)
                .eq(ElectricianOrganizationFamily::getOrgId, orgId);
        List<ElectricianOrganizationFamily> relations = this.baseMapper.selectList(wrapper);
        List<String> electricianIds = relations.stream().map(ElectricianOrganizationFamily::getElectricianId).toList();
        return ResponseResult.ok(electricianIds);
    }

    /*
     * 根据组织ID查询电工组织关系
     */
    @Override
    public ResponseResult<List<String>> getElectriciansByOrgId(String orgId) {
        if (StringUtils.isBlank(orgId)) {
            return ResponseResult.parameterError(null, "组织ID不能为空");
        }
        LambdaQueryWrapper<ElectricianOrganizationFamily> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ElectricianOrganizationFamily::getOrgId, orgId);
        List<ElectricianOrganizationFamily> relations = this.baseMapper.selectList(wrapper);
        List<String> electricianIds = relations.stream().map(ElectricianOrganizationFamily::getElectricianId).toList();
        return ResponseResult.ok(electricianIds);
    }

    private Boolean existsByOrgIdAndElectricianId(String orgId, String electricianId) {
        LambdaQueryWrapper<ElectricianOrganizationFamily> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ElectricianOrganizationFamily::getOrgId, orgId)
                .eq(ElectricianOrganizationFamily::getElectricianId, electricianId);
        return this.count(wrapper) > 0;
    }

    private Boolean existsByFamilyIdAndElectricianId(String familyId, String electricianId) {
        LambdaQueryWrapper<ElectricianOrganizationFamily> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ElectricianOrganizationFamily::getFamilyId, familyId)
                .eq(ElectricianOrganizationFamily::getElectricianId, electricianId);
        return this.count(wrapper) > 0;
    }
}
